package com.tanyoujie.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tanyoujie.cart.interceptor.CartInterceptor;
import com.tanyoujie.cart.feign.ProductFeignService;
import com.tanyoujie.cart.service.CartService;
import com.tanyoujie.cart.to.UserInfoTo;
import com.tanyoujie.cart.vo.CartItemVo;
import com.tanyoujie.cart.vo.CartVo;
import com.tanyoujie.cart.vo.SkuInfoVo;
import com.tyj.common.constant.CartConstant;
import com.tyj.common.exception.BizCodeEnume;
import com.tyj.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItemVo addToCart(Long skuId, Integer count) {
        //得到当前用户操作redis的工具对象
        BoundHashOperations<String, Object, Object> ops = getCartItemOps();
        // 判断当前商品是否已经存在购物车
        String cartJson = (String) ops.get(skuId.toString());
        if (!StringUtils.isEmpty(cartJson)){
            CartItemVo cartItemVo=new CartItemVo();
            // 1 已经存在购物车，将数据取出并添加商品数量
            cartItemVo = JSON.parseObject(cartJson, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+count);
            String json=JSON.toJSONString(cartItemVo);
            ops.put(skuId.toString(),json);
            return cartItemVo;
        }else {
            //2  没有存在购物车,添加新的商品
            //远程调用查看当前sku基本信息
            CartItemVo cartItemVo=new CartItemVo();

            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setCheck(true);
                cartItemVo.setCount(count);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setTitle(skuInfo.getSkuTitle());
            }, threadPoolExecutor);

            CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
                //2.2 远程查询sku属性组合信息
                List<String> attrValuesAsString = productFeignService.getSkuSaleAttrValuesAsString(skuId);
                cartItemVo.setSkuAttrValues(attrValuesAsString);
            }, threadPoolExecutor);

            try {
                CompletableFuture.allOf(future1, future2).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            String jsonString = JSON.toJSONString(cartItemVo);
            ops.put(skuId.toString(),jsonString);
            return cartItemVo;
        }


    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartItemOps();
        String json= (String) ops.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(json, CartItemVo.class);
        return cartItemVo;
    }

    @Override
    public CartVo getCart() {
        //判断该用户否是为登录用户
        CartVo cartVo=new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        List<CartItemVo> tempCart= getCartByKey(userInfoTo.getUserKey());
        if (!StringUtils.isEmpty(userInfoTo.getUserId())){
            //2 用户登录
            //2.2 查询user-key对应的临时购物车，并和用户购物车合并
            if (tempCart!=null&&tempCart.size()>0){
                for (CartItemVo cartItemVo : tempCart) {
                    //2.3 在redis中更新数据
                    addToCart(cartItemVo.getSkuId(), cartItemVo.getCount());
                }
            }
            //获取合并后的购物车
            List<CartItemVo> userCart = getCartByKey(userInfoTo.getUserId().toString());
            cartVo.setItems(userCart);
            //2.4 删除临时购物车数据
            redisTemplate.delete(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
        }else {
            //不为登录用户 获取当前用户的临时购物车
            cartVo.setItems(tempCart);
        }
        return cartVo;
    }

    @Override
    public R editCartCount(Long skuId, Integer count) {
        try{
            BoundHashOperations<String, Object, Object> ops = getCartItemOps();
            String json = (String) ops.get(skuId.toString());
            CartItemVo cartItemVo = JSON.parseObject(json, CartItemVo.class);
            cartItemVo.setCount(count);
            String string = JSON.toJSONString(cartItemVo);
            ops.put(skuId.toString(),string);
        }catch (Exception e){
            log.error("修改购物车数量出现问题{}",e.getMessage());
            return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    @Override
    public void deleteCart(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartItemOps();
        ops.delete(skuId.toString());
    }

    @Override
    public Long getCartNum() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (StringUtils.isEmpty(userInfoTo.getUserId())) {
            //没有登录使用临时购物车
            Long size = redisTemplate.opsForHash().size(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
            return size;
        } else {
            //登录了 使用用户购物车
            Long size = redisTemplate.opsForHash().size(CartConstant.CART_PREFIX + userInfoTo.getUserId());
            return size;
        }

    }

    @Override
    public void checkCart(boolean isChecked, Integer skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartItemOps();
        //取出该对象 修改
        String cartInfoJson= (String) ops.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(cartInfoJson, CartItemVo.class);
        cartItemVo.setCheck(isChecked);

        //放回redis覆盖
        ops.put(skuId.toString(),JSON.toJSONString(cartItemVo));

    }

    @Override
    public List<CartItemVo> getCheckedItems() {
        log.debug("线程{}号执行任务",Thread.currentThread().getName());
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        List<CartItemVo> cartByKey = getCartByKey(userInfoTo.getUserId().toString());
        List<CartItemVo> collect = cartByKey.stream().filter((cartItemVo) -> cartItemVo.getCheck()).collect(Collectors.toList());
        return collect;
    }

    /**
     * 通过名字获取购物车的数据
     */
    private List<CartItemVo> getCartByKey(String userKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(CartConstant.CART_PREFIX+userKey);
        List<Object> values = ops.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> cartItemVos = values.stream().map(obj -> {
                String json = (String) obj;
                return JSON.parseObject(json, CartItemVo.class);
            }).collect(Collectors.toList());
            return cartItemVos;
        }
        return null;
    }


    /**
     * 得到当前用户操作redis的工具对象
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartItemOps() {
        //1判断是否已经登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1.1 登录使用userId操作redis
        if (!StringUtils.isEmpty(userInfoTo.getUserId())) {
            return redisTemplate.boundHashOps(CartConstant.CART_PREFIX + userInfoTo.getUserId());
        } else {
            //1.2 未登录使用user-key操作redis
            return redisTemplate.boundHashOps(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
        }
    }
}
